package tetris;

public class CharBoard implements Board<String> {
    private final int rows;
    private final int columns;
    private int activeBlockColumn;
    private int activeBlockRow;
    private char[][] board;
    private boolean isGameOver;

    public CharBoard(int rows, int columns) {
        if (rows < 2 || columns < 2) {
            throw new IllegalArgumentException();
        }
        this.rows = rows;
        this.columns = columns;

        board = new char[rows][columns];
        initBoard();

        activeBlockColumn = -1;
        activeBlockRow = -1;

        isGameOver = false;
    }

    private void initBoard() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                board[i][j] = '*';
            }
        }
    }

    @Override
    public String render() {
        StringBuilder boardBuilder = new StringBuilder();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                boardBuilder.append(getCharAt(i, j));
            }
            if (i != rows - 1) {
                boardBuilder.append('\n');
            }
        }
        return boardBuilder.toString();
    }

    private char getCharAt(int i, int j) {
        if (i == activeBlockRow && j == activeBlockColumn) {
            return 'Y';
        }
        else {
            return board[i][j];
        }
    }

    @Override
    public void tick() {
        if (activeBlockColumn == -1 && activeBlockRow == -1) {
            throwNewBlock();
        }
        else {
            int nextBlockRow = activeBlockRow + 1;
            if (nextBlockRow == rows || board[nextBlockRow][activeBlockColumn] != '*') {
                board[activeBlockRow][activeBlockColumn] = 'Y';
                throwNewBlock();
            } else {
                activeBlockRow = nextBlockRow;
            }
        }
    }

    private void throwNewBlock() {
        activeBlockColumn = (columns - 1) / 2;
        activeBlockRow = 0;
        if (board[activeBlockRow][activeBlockColumn] != '*') {
            isGameOver = true;
        }
    }

    @Override
    public boolean isGameOver() {
        return isGameOver;
    }
}
